<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>修改密码</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="rePasswordForma"
      :rules="rePasswordRules"
      ref="rePasswordForma"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="rePasswordForma.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="rePasswordForma.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="rePasswordForma.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateInfo">修改密码</el-button>
        <el-button type="info" @click="$refs.rePasswordForma.resetFields()"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updatepwd } from 'network/user'

export default {
  name: 'VueEv2Repassword',

  data () {
    const oldPassword = (rule, value, callback) => {
      if (value === this.rePasswordForma.old_pwd) {
        return callback(new Error('新旧密码不能相同'))
      }
      callback()
    }
    const isPassword = (rule, value, callback) => {
      if (value !== this.rePasswordForma.new_pwd) {
        return callback(new Error('两次密码不一致'))
      }
      callback()
    }
    return {
      rePasswordForma: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rePasswordRules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码的必须是6-15位的非空字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码的必须是6-15位的非空字符', trigger: 'blur' },
          { validator: oldPassword, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码的必须是6-15位的非空字符', trigger: 'blur' },
          { validator: isPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updateInfo () {
      this.$refs.rePasswordForma.validate(async valid => {
        if (!valid) return
        const { data: res } = await updatepwd(this.rePasswordForma)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$refs.rePasswordForma.resetFields()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
